package com.aiyige.utils.prefs;

import android.content.Context;

public abstract class PrefsHelper {
	private final Context mContext;
	private final String mName;
	private final int mNewVersion;
	private Prefs mPrefs = null;

	public PrefsHelper(Context context, String name, int version) {
		if (version < 1) {
			throw new IllegalArgumentException("Version must be >= 1, was "
					+ version);
		}
		mContext = context;
		mName = name;
		mNewVersion = version;
	}

	public String getPrefsName() {
		return mName;
	}

	public synchronized Prefs getPrefs() {
		if (mPrefs != null) {
			return mPrefs;
		}
		Prefs prefs = new Prefs(mContext, mName);
		int version = prefs.getVersion();
		if (version != mNewVersion) {
			if (version == 0) {
				onCreate(prefs);
			} else {
				if (version > mNewVersion) {
					onDowngrade(prefs, version, mNewVersion);
				} else if(version < mNewVersion){
					onUpgrade(prefs, version, mNewVersion);
				}
			}
			prefs.setVersion(mNewVersion);
		}
		mPrefs=prefs;
		return prefs;
	}

	public abstract void onCreate(Prefs prefs);

	public abstract void onUpgrade(Prefs prefs, int oldVersion, int newVersion);

	public void onDowngrade(Prefs prefs, int oldVersion, int newVersion) {
		throw new IllegalArgumentException(
				"Can't downgrade prefs from version " + oldVersion + " to "
						+ newVersion);
	}
}
